package com.ojoin.trade.common.utils.mail;

import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.Vector;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.mail.util.ByteArrayDataSource;

import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.CommonUtils;

public class SendMail {

	public String toChinese(String text) {
		try {
			text = MimeUtility.encodeText(new String(text.getBytes(), "UTF-8"),
					"UTF-8", "B");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return text;
	}

	public boolean sendMail(MailBean mb) {
		String host = mb.getHost();
		final String username = mb.getUsername();
		final String password = mb.getPassword();
		String from = mb.getFrom();
		String fromshortname = mb.getFromshortname();
		String to = mb.getTo();
		String cc = mb.getCc();
		String subject = mb.getSubject();
		String content = mb.getContent();
		String fileName = mb.getFilename();
		Vector<String> file = mb.getFile();
		HashMap<String, byte[]> bytefiles = mb.getBytefiles();

		Properties props = System.getProperties();
		props.put("mail.smtp.host", host); // 设置SMTP的主机
		props.put("mail.smtp.auth", "true"); // 需要经过验证

		Session session = Session.getInstance(props, new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, password);
			}
		});

		try {
			MimeMessage msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress(from, fromshortname));
			String[] toAddress = to.split(";");

			List<InternetAddress> tolist = new ArrayList<InternetAddress>();// 不能使用string类型的类型，这样只能发送一个收件人
			for (int i = 0; i < toAddress.length; i++) {
				tolist.add(new InternetAddress(toAddress[i]));
			}
			InternetAddress[] toAddressArray = (InternetAddress[]) tolist
					.toArray(new InternetAddress[tolist.size()]);

			List<InternetAddress> cclist = new ArrayList<InternetAddress>();// 不能使用string类型的类型，这样只能发送一个收件人
			if (!CommonUtils.isEmpty(cc)) {
				String[] ccAddress = cc.split(";");
				for (int i = 0; i < ccAddress.length; i++) {
					cclist.add(new InternetAddress(ccAddress[i]));
				}
			}
			InternetAddress[] ccAddressArray = (InternetAddress[]) cclist
					.toArray(new InternetAddress[cclist.size()]);

			msg.setRecipients(Message.RecipientType.TO, toAddressArray);
			msg.setRecipients(Message.RecipientType.CC, ccAddressArray);

			msg.setSubject(subject);
			Multipart mp = new MimeMultipart();
			MimeBodyPart mbpContent = new MimeBodyPart();
			mbpContent.setContent(content, "text/html;charset=UTF-8"); // 指定编码格式
			mp.addBodyPart(mbpContent);

			/* 往邮件中添加附件 */
			if (file != null) {
				Enumeration<String> efile = file.elements();
				while (efile.hasMoreElements()) {
					MimeBodyPart mbpFile = new MimeBodyPart();
					fileName = efile.nextElement().toString();
					FileDataSource fds = new FileDataSource(fileName);
					mbpFile.setDataHandler(new DataHandler(fds));
					mbpFile.setFileName(toChinese(fds.getName()));
					mp.addBodyPart(mbpFile);
				}
			}

			/* 往邮件中添加byte数组生成的附件 */
			if (bytefiles != null) {
				Set<String> keySet = bytefiles.keySet();
				Iterator<String> it = keySet.iterator();
				while (it.hasNext()) {
					String filename = it.next();
					byte[] bs = bytefiles.get(filename);
					ByteArrayDataSource fds = null;
					// TODO:不同类型补充对应附件文件类型
					if (filename.endsWith("xls")) {
						fds = new ByteArrayDataSource(bs,
								"application/vnd.ms-excel");
					} else {
						fds = new ByteArrayDataSource(bs, "text/plain");
					}
					MimeBodyPart mbpFile = new MimeBodyPart();
					mbpFile.setDataHandler(new DataHandler(fds));
					mbpFile.setFileName(toChinese(filename));
					mp.addBodyPart(mbpFile);
				}
			}

			msg.setContent(mp);
			msg.setSentDate(new Date());
			Transport.send(msg);

		} catch (Exception me) {
			me.printStackTrace();
			throw new BusinessException("邮件通道异常", me);
		}
		return true;
	}

}
